<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use DateTimeInterface;

class BaseModel extends Model
{
    public $timestamps = true;
    const CREATED_AT = 'ctime';
    const UPDATED_AT = 'mtime';
    static $maxLimit = 1000;
    static $cacheSeconds = 3600;
    static $tables = [];
    static $deleted = 1;
    static $noDeleted = 0;

    /**
     * 查询一条信息
     * @param array $where
     * @param string $field
     * @return mixed
     */
    public static function getInfo($where = [], $field = '*')
    {
        if ($field != '*') {
            $field = explode(',', $field);
        }
        $info = self::where($where)->select($field)->orderBy('id', 'desc')->first();
        if (!empty($info)) {
            $info = $info->toArray();
        }
        return $info;
    }

    /**
     * 查询多条数据
     * @param array $where
     * @param string $field
     * @return mixed
     */
    public static function getList($where = [], $field = '*')
    {
        if ($field != '*') {
            $field = explode(',', $field);
        }
        $list = self::where($where)->select($field)->get();
        if (!empty($list)) {
            $list = $list->toArray();
        }
        return $list;
    }

    static public function getToPageByBuilder($builder)
    {
        $total = $builder->count();
        $page = request('page', 1);
        $pageSize = request('page_size', 20);
        $pageSize = $pageSize > self::$maxLimit ? self::$maxLimit : $pageSize;
        $page = $page > 0 ? $page - 1 : 0;
        $data = $builder->skip($page * $pageSize)->take($pageSize)->get()->toArray();
        return array(
            'data' => $data,
            'total' => $total,
            'pageData' => [
                'total' => $total,
                'current_page' => ($page + 1),
                'total_page' => ceil($total / $pageSize),
                'page_size' => $pageSize
            ]
        );
    }

    /**
     * @return string table name
     * @author    zhe.wang
     * @desc        获取model表名
     * @example YourModel::getTableName()
     */
    static public function getTableName()
    {
        $model = static::class;
        if (!isset(self::$tables[$model])) {
            self::$tables[$model] = (new $model())->getTable();
        }
        return self::$tables[$model];
    }

    /**
     * Desc: 自动转化时间格式
     * Time: 2021/4/16 10:12
     * @param DateTimeInterface $date
     * @return string
     */
    protected function serializeDate(DateTimeInterface $date)
    {
        return $date->format('Y-m-d H:i:s');
    }
}
